﻿@using JavaDevToys.Rcl.Service
@using System.Text
<script>
    var require = { paths: { 'vs': 'https://cdn.masastack.com/npm/monaco-editor/0.34.1/min/vs' } };
</script>
<script src="https://cdn.masastack.com/npm/monaco-editor/0.34.1/min/vs/loader.js"></script>
<script src="https://cdn.masastack.com/npm/monaco-editor/0.34.1/min/vs/editor/editor.main.nls.js"></script>
<script src="https://cdn.masastack.com/npm/monaco-editor/0.34.1/min/vs/editor/editor.main.js"></script>


<MDialog @bind-Value="@_ShowDialog"

Fullscreen
Persistent
Transition="dialog-bottom-transition">
    <ActivatorContent>
        @ActivatorContent
    </ActivatorContent>
    <ChildContent>
        <MContainer Class="d-flex flex-column">
            <MRow>
                <MCardTitle>已有代码合并:{@cuss}/{@count}</MCardTitle>
            </MRow>
            <!-- 编辑器布局 -->
            <MRow>
                <MCol Cols="6">
                    <MCard>
                        <MCardTitle>现有代码</MCardTitle>
                        <MCardText>
                            <MMonacoEditor Id="@Guid.NewGuid().ToString()" Height="800" Width="@("100%")" MaxWidth="800" InitOptions="InitOldEditor" @ref="_oldEditor"></MMonacoEditor>
                        </MCardText>
                    </MCard>
                </MCol>
                <MCol Cols="6">
                    <MCard>
                        <MCardTitle>修改后代码</MCardTitle>
                        <MCardText>
                            <MMonacoEditor Id="@Guid.NewGuid().ToString()" Height="800" Width="@("100%")" MaxWidth="800" InitOptions="InitNewEditor" @ref="_newEditor"></MMonacoEditor>
                        </MCardText>
                    </MCard>
                </MCol>
            </MRow>

            <!-- 按钮区域 -->
            <div Class="d-flex justify-end align-center flex-wrap" Style="gap: 8px;">
                <MButton Color="green darken-1"
                Text
                OnClick="Cover">
                    @CoverBtnTitle
                </MButton>
                <MButton Color="green darken-1"
                Text
                OnClick="() => ShowDialog = false">
                    关闭
                </MButton>
            </div>

        </MContainer>
    </ChildContent>
</MDialog>

@code {
    [Parameter]
    public RenderFragment ActivatorContent { get; set; }
    private bool _ShowDialog;
    [Parameter]
    public bool ShowDialog
    {
        get => _ShowDialog;
        set
        {
            if (value != _ShowDialog)
            {
                _ShowDialog = value;
                ShowDialogChanged.InvokeAsync(value);
            }
            if (value)
            {
                InitializeEditors();
            }
        }
    }
    [Parameter]
    public Dictionary<string, string> NewMothedDict { get; set; }
    [Inject]
    public IJavaFileService javaFileService { get; set; }
    private MMonacoEditor _oldEditor;
    private MMonacoEditor _newEditor;

    [Parameter]
    public EventCallback<bool> ShowDialogChanged { get; set; }

    private int count = 0;
    private int cuss = 1;

    private string CoverBtnTitle = "覆盖";

    protected override void OnInitialized()
    {
        NewMothedDict = new Dictionary<string, string>();
        base.OnInitialized();
    }

    private void InitializeEditors()
    {
        count = NewMothedDict.Count;
        cuss = 1;

        if (cuss < count)
        {
            CoverBtnTitle = "覆盖并加载下一个";
        }
        else
        {
            CoverBtnTitle = "覆盖并关闭";
        }
        var javaCode = string.Empty;
        if (NewMothedDict?.Count > 0)
        {
            javaCode = javaFileService.ReadFileAllText(NewMothedDict.FirstOrDefault().Key);
        }
        string[] lines = javaCode.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

        for (int i = lines.Length - 1; i >= 0; i--)
        {
            if (lines[i].Contains('}'))
            {
                if (i > 0) // 确保不是第一行
                {
                    lines[i - 1] += Environment.NewLine + NewMothedDict.FirstOrDefault().Value;
                }
                break; // 只处理最后一次匹配，找到后退出
            }
        }
        string newCode = string.Join(Environment.NewLine, lines);
        _oldEditor?.SetValueAsync(javaCode);
        _newEditor?.SetValueAsync(newCode);
    }

    private async Task<object> InitOldEditor()
    {
        var javaCode = string.Empty;
        if (NewMothedDict?.Count > 0)
        {
            javaCode=javaFileService.ReadFileAllText(NewMothedDict.FirstOrDefault().Key);
        }
        object options = new
        {
            value = javaCode,
            language = "java",
            lineNumbers = "on",
            roundedSelection = false,
            scrollBeyondLastLine = false,
            readOnly = false,
            theme = "vs-dark",
        };
        count = NewMothedDict.Count;
        cuss = 1;
        if (cuss < count)
        {
            CoverBtnTitle = "覆盖并加载下一个";
        }
        return options;
    }

    private async Task<object> InitNewEditor()
    {
        var javaCode = string.Empty;
        if (NewMothedDict?.Count > 0)
        {
            javaCode = javaFileService.ReadFileAllText(NewMothedDict.FirstOrDefault().Key);
        }
        string[] lines = javaCode.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

        for (int i = lines.Length - 1; i >= 0; i--)
        {
            if (lines[i].Contains('}'))
            {
                if (i > 0) // 确保不是第一行
                {
                    lines[i - 1] += Environment.NewLine + NewMothedDict.FirstOrDefault().Value;
                }
                break; // 只处理最后一次匹配，找到后退出
            }
        }
        string newCode = string.Join(Environment.NewLine, lines);
        object options = new
        {
            value = newCode,
            language = "java",
            lineNumbers = "on",
            roundedSelection = false,
            scrollBeyondLastLine = false,
            readOnly = false,
            theme = "vs-dark",
        };
        return options;
    }

    private async void Cover(){
        string code=await _newEditor.GetValueAsync();
        File.WriteAllText(NewMothedDict.FirstOrDefault().Key, code, new UTF8Encoding(false));
        NewMothedDict.Remove(NewMothedDict.FirstOrDefault().Key);
        if (NewMothedDict.Count()>0){
            var javaCode = javaFileService.ReadFileAllText(NewMothedDict.FirstOrDefault().Key);
            object oldOptions = new
            {
                value = javaCode,
                language = "java",
                lineNumbers = "on",
                roundedSelection = false,
                scrollBeyondLastLine = false,
                readOnly = false,
                theme = "vs-dark",
            };
            string[] lines = javaCode.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

            for (int i = lines.Length - 1; i >= 0; i--)
            {
                if (lines[i].Contains('}'))
                {
                    if (i > 0) // 确保不是第一行
                    {
                        lines[i - 1] += Environment.NewLine + NewMothedDict.FirstOrDefault().Value;
                    }
                    break; // 只处理最后一次匹配，找到后退出
                }
            }
            string newCode = string.Join(Environment.NewLine, lines);
            object newOptions = new
            {
                value = newCode,
                language = "java",
                lineNumbers = "on",
                roundedSelection = false,
                scrollBeyondLastLine = false,
                readOnly = false,
                theme = "vs-dark",
            };
            await _oldEditor.SetValueAsync(javaCode);
            await _newEditor.SetValueAsync(newCode);
            // await _oldEditor.UpdateOptionsAsync(oldOptions);
            // await _newEditor.UpdateOptionsAsync(newOptions);
        }else{
            ShowDialog = false;
        }
        cuss++;
        if (cuss == count)
        {
            CoverBtnTitle = "覆盖并关闭";
        }
        StateHasChanged();
    }
}
